﻿using K8.CBB;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.Reflection;

namespace KingerRobot.SailunWebService;
class StartHelper
{
    #region 单例模式
    //private static readonly object lockobject = new object();
    public static StartHelper Instance { get { return Singleton.Create<StartHelper>(); } }
    /// <summary>
    /// 构造函数
    /// </summary>
    private StartHelper()
    {
    }
    #endregion

    private void startApi(int port)
    {
        var url = $"http://*:{port}/";
        XTask.Once(() => { runWebApiServer(url); });
    }
    private void runWebApiServer(string url)
    {
        try
        {
            Host.CreateDefaultBuilder()
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  webBuilder.ConfigureKestrel(options =>
                  {
                      options.Limits.MaxRequestBufferSize = int.MaxValue;
                      options.Limits.MaxResponseBufferSize = int.MaxValue;
                      options.Limits.MaxRequestBodySize = int.MaxValue;
                      options.Limits.MaxRequestLineSize = int.MaxValue;
                  });
                  webBuilder.UseUrls(url);
                  webBuilder.UseStartup<Startup>();
              })
            .Build()
            .Run();
        }
        catch (Exception ex)
        {
            throw new System.Exception($"API启动失败>>{url}", ex);
        }
    }
    public int Start(Action<string> msg)
    {
        if (string.IsNullOrWhiteSpace(XApp.Current.AppId))
        {
            InitializeService(msg);
        }
        if (XApp.Current == null)
        {
            return 0;
        }
        var port = K8.CBB.XApp.Current.WpiPort;
        startApi(port);
        return port;
    }
    private void InitializeService(Action<string> msg)
    {
        var typeName = "KingerRobot.RSF.Client.RfsServerStartHelper,KingerRobot.RSF.Client";
        var type = typeName.ToType();
        if (type == null)
        {
            return;
        }
        msg($"启动服务[{typeName}]……");
        var instance = type.GetProperty("Instance").GetValue(null);
        var method = instance.GetType().GetMethod("InitializeService", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        method.Invoke(instance, new object[] { msg });
    }
}
